<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="menuDialogFormRef" :model="state.menuInfo" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级菜单">
							<el-cascader
								:options="state.menuData"
								:props="{ emitPath:false, checkStrictly: true, value: 'id', label: 'title' }"
								placeholder="选择上级菜单"
								clearable
								class="w100"
								v-model="state.menuInfo.parentId"
							>
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单名称">
							<el-input v-model="state.menuInfo.meta.title" placeholder="格式：message.router.xxx"
								clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="路由名称">
							<el-input v-model="state.menuInfo.name" placeholder="路由中的 name 值" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="路由路径">
							<el-input v-model="state.menuInfo.path" placeholder="路由中的 path 值" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序">
							<el-input v-model="state.menuInfo.sequence" placeholder="排序号" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="重定向">
							<el-input v-model="state.menuInfo.redirect" placeholder="请输入路由重定向" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单图标">
							<IconSelector placeholder="请输入菜单图标" v-model="state.menuInfo.meta.icon" />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="组件路径">
							<el-input v-model="state.menuInfo.component" placeholder="组件路径" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="链接地址">
							<el-input v-model="state.menuInfo.meta.isLink" placeholder="外链/内嵌时链接地址（http:xxx.com）"
								clearable :disabled="!state.menuInfo.isLink">
							</el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="权限标识">
							<el-select v-model="state.menuInfo.roleCodeList" multiple placeholder="选择角色" clearable
								class="w100">
								<el-option v-for="option in state.roleOption" :key="option.roleCode"
									:label="option.roleName" :value="option.roleCode" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否隐藏">
							<el-radio-group v-model="state.menuInfo.meta.isHide">
								<el-radio :value="true">隐藏</el-radio>
								<el-radio :value="false">不隐藏</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="页面缓存">
							<el-radio-group v-model="state.menuInfo.meta.isKeepAlive">
								<el-radio :value="true">缓存</el-radio>
								<el-radio :value="false">不缓存</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否固定">
							<el-radio-group v-model="state.menuInfo.meta.isAffix">
								<el-radio :value="true">固定</el-radio>
								<el-radio :value="false">不固定</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否外链">
							<el-radio-group v-model="state.menuInfo.isLink" :disabled="state.menuInfo.meta.isIframe">
								<el-radio :value="true">是</el-radio>
								<el-radio :value="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否内嵌">
							<el-radio-group v-model="state.menuInfo.meta.isIframe" @change="onSelectIframeChange">
								<el-radio :value="true">是</el-radio>
								<el-radio :value="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { useMenuApi } from '/@/api/menu';
import { useRoleApi } from '/@/api/role';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义变量内容
const menuDialogFormRef = ref();
const menuApi = useMenuApi();
const roleApi = useRoleApi();

const state = reactive({
	menuInfo: {
		id: '',
		parentId: '',
		name: '', 					// 路由名称
		component: '', 				// 组件路径
		componentAlias: '', 		// 组件路径别名
		isLink: false, 				// 是否外链
		path: '', 					// 路由路径
		sequence: '',				//排序
		redirect: '', 				// 路由重定向，有子集 children 时
		roleCodeList: [], 			// 权限标识，取角色管理
		meta: {
			title: '', 				// 菜单名称
			icon: '', 				// 菜单图标
			isHide: false, 			// 是否隐藏
			isKeepAlive: true, 		// 是否缓存
			isAffix: false, 		// 是否固定
			isLink: '', 			// 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
			isIframe: false, 		// 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
		},
	},
	menuData: [] as Menu[], // 上级菜单数据
	roleOption: [] as Role[],
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 根据id获取菜单对应的名称
const getMenuName = (menuId: number, menuList: Menu[]) => {
	const nextMenuList: Menu[] = [];
	for (const val of menuList) {
		if (menuId === val.id) {
			return val.meta.title;
		}
		if (val.children) nextMenuList.push(...val.children);
	}
	if (nextMenuList.length > 0) {
		return getMenuName(menuId, nextMenuList);
	}
}

// 清空menuInfo
const clearMenuInfo = () => {
	state.menuInfo = {
		id: '',
		parentId: '',
		name: '', 					// 路由名称
		component: '', 				// 组件路径
		componentAlias: '', 		// 组件路径别名
		isLink: false, 				// 是否外链
		path: '', 					// 路由路径
		sequence: '',				//排序
		redirect: '', 				// 路由重定向，有子集 children 时
		roleCodeList: [], 			// 权限标识，取角色管理
		meta: {
			title: '', 				// 菜单名称
			icon: '', 				// 菜单图标
			isHide: false, 			// 是否隐藏
			isKeepAlive: true, 		// 是否缓存
			isAffix: false, 		// 是否固定
			isLink: '', 			// 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
			isIframe: false, 		// 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
		},
	}
}

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	console.log(state.menuData);
	if (type === 'edit') {
		console.log(row);
		state.menuInfo = JSON.parse(JSON.stringify(row));
		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
	} else {
		clearMenuInfo();
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 是否内嵌下拉改变
const onSelectIframeChange = () => {
	if (state.menuInfo.meta.isIframe) state.menuInfo.isLink = true;
	else state.menuInfo.isLink = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 提交
async function onSubmit() {
	await menuApi.editMenu(state.menuInfo);

	closeDialog(); // 关闭弹窗
	emit('refresh');
};

// 页面加载时
onMounted(() => {
	initMenuTree();
	initRoleOption();
});

// 构建角色枚举值
async function initRoleOption() {
	const roleData = await roleApi.allRoleList();
	if (roleData.data.length <= 0)
		return Promise.resolve(true);
	const roleList: Role[] = roleData.data.rows;
	state.roleOption = roleList;
}

// 构建上级菜单树
async function initMenuTree() {
	const menuData = await menuApi.authMenuList();
	if (menuData.data.length <= 0)
		return Promise.resolve(true);

	const menuList: Menu[] = menuData.data.rows;
	state.menuData = getMenuData(menuList[0].children);
}

// 获取 pinia 中的路由
const getMenuData = (routes: RouteItems) => {
	const arr: RouteItems = [];
	routes.map((val: RouteItem) => {
		val['title'] = val.meta?.title as string;
		arr.push({ ...val });
		if (val.children) getMenuData(val.children);
	});
	return arr;
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
